import VueRouter from "vue-router";
import CvsLogin from "@/views/Login/index.vue";
import SysUser from "@/views/SysUser/index.vue";
import Home from "@/views/Home/index.vue";
import UpdateUser from "@/views/SysUser/UpdateUser.vue";
import {getToken} from "@/utils/auth";
import store from "@/store";
import {Message} from "element-ui";
import CvsFrame from "@/components/common/CvsFrame.vue";

// 声明验证白名单
const whiteList = ['/login']

// 创建一个路由器
const router = new VueRouter({
    routes: [
        // 登录页面
        {
            path: '/login',
            component: CvsLogin,
            hidden: true
        },
        {
            path: '/',
            component: Home,
            redirect: '/frame',
            children: [
                {
                    path: 'frame',
                    component: CvsFrame
                },
                {
                    path: 'user',
                    component: SysUser,
                    children: [
                        {
                            path: 'update/:id',
                            component: UpdateUser

                        }
                    ]
                }
            ]
        },
    ]
})

// 全局前置路由守卫----初始化时被调用、每次路由切换前调用,可以控制权限
router.beforeEach((to, from, next) => {
    // 先从cookie中取出token
    const token = getToken();
    if (token) {
        if (to.path === '/') {
            store.dispatch('getInfo').then(() => {
                // 如果已登录，则直接跳转首页
                next({path: '/'});
            })
        } else {
            const userName = store.state.name
            if (userName) {
                //     如果有用户名，则直接进入下一步
                next();
            } else {
                store.dispatch('getInfo').then(() => {
                    next()
                }).catch((error) => {
                    //     重置token
                    store.dispatch('resetToken').then(() => {
                        Message.error(error || 'Has Error');
                        //     重定向到login页面
                        next(`/login?redirect=${to.path}`)
                    })
                })
            }
        }
    } else {
        //     如果 没有token,判断是否在白名单内
        if (whiteList.indexOf(to.path) !== -1) {
            //     直接放行
            next();
        } else {
            //     重定向到login页面
            next(`/login?redirect=${to.path}`)
        }
    }
})

// 暴露路由器
export default router
